<template>
  <div id="home">
    <div class="common-layout">
      <div>
        <div class="home-container-content">
          <el-row :gutter="20" class="">
            <el-col :sm="16" :xs="24" class="">
              <!-- 近期比赛 -->
              <div class="my-home-div">
                <div :style="{ minHeight: '350px' }">
                  <div class="my-home-div-line flex-jc-space-between">
                    <div class="">
                      <i class="icon icon-ic_fluent_flag_16_filled"></i>
                      近期比赛
                    </div>
                    <div class="text-right" :style="{ width: '110px' }">
                      <router-link class="href" :to="{ name: '竞赛' }"
                        >查看更多</router-link
                      >
                    </div>
                  </div>
                  <!-- 比赛 -->
                  <activity-list
                    :activitys="getactivity.slice(0, 5)"
                  ></activity-list>
                </div>
              </div>
              <el-row :gutter="20" class="">
                <!-- 左侧 -->
                <el-col :md="13" :xs="24" class="" :style="{}">
                  <!-- 题目搜索 -->
                  <el-row class="" :gutter="20">
                    <el-col :md="8" :sm="8" :xs="8">
                      <div class="my-home-div">
                        <div class="my-home-div-line">
                          <i
                            class="icon icon-ic_fluent_book_number_16_filled"
                          ></i>
                          题目搜索
                        </div>
                        <div class="my-home-question-input-box">
                          <el-select
                            size="default"
                            v-model="question"
                            filterable
                            remote
                            placeholder="题目名称或ID"
                            clearable
                            :remote-method="remoteSelectQuestion"
                            @change="qChange"
                            :loading="loading"
                          >
                            <el-option
                              v-for="item in options"
                              :key="item.ID"
                              :label="item.name"
                              :value="item.ID!"
                            >
                              <span style="margin-right: 20px">{{
                                item.ID
                              }}</span>
                              <span
                                style="
                                  color: var(--el-text-color-secondary);
                                  font-size: 13px;
                                "
                              >
                                {{ item.name }}
                              </span>
                            </el-option>
                          </el-select>
                        </div>
                      </div>
                    </el-col>
                    <!-- 最近练习 -->
                    <el-col :md="16" :sm="16" :xs="16">
                      <div class="my-home-div">
                        <div class="my-home-div-line">
                          <i
                            class="icon icon-ic_fluent_book_number_16_filled"
                          ></i>
                          最近练习
                        </div>
                        <div class="my-home-question-box">
                          <el-row class="">
                            <el-col
                              v-for="(item, k) in myFinishQ"
                              :span="8"
                              class="cursor-pointer"
                              :title="item.question?.name"
                              @click="goToQuestion(item)"
                              :key="k"
                            >
                              <div class="my-home-question">
                                <el-text
                                  class="hover-color"
                                  truncated
                                  size="default"
                                >
                                  {{ item.question?.name }}
                                </el-text>
                                <i
                                  class="icon-ic_fluent_arrow_circle_right_24_filled"
                                  :style="{
                                    color: 'var(--color-cheng)',
                                    verticalAlign: 'middle',
                                  }"
                                >
                                </i>
                              </div>
                            </el-col>
                          </el-row>
                        </div>
                      </div>
                    </el-col>
                  </el-row>
                  <!-- 历年真题 -->
                  <div class="my-home-div">
                    <div class="my-home-div-line position-relative">
                      <span>
                        <i
                          class="icon icon-ic_fluent_clipboard_code_24_filled"
                        ></i>
                        历年真题
                      </span>
                      <div
                        class="position-absolute top-0"
                        :style="{
                          lineHeight: '47px',
                          fontSize: '14px',
                          right: '12px',
                        }"
                      >
                        <router-link
                          class="href"
                          :to="{
                            name: '题单',
                            query: {
                              tabName: 'evaluation',
                              purpose: '能力测评',
                            },
                          }"
                          >查看更多</router-link
                        >
                      </div>
                    </div>
                    <div class="m-p-3 m-0">
                      <router-link
                        v-for="v in 能力测评"
                        :key="`能力测评_${v.ID}`"
                        :to="{
                          name: '题库列表',
                          params: { ID: v.ID },
                          query: { istest: 1 },
                        }"
                        v-slot="{ navigate }"
                        custom
                      >
                        <div
                          class="jhfontweight cu home-item-list position-relative"
                          @click="navigate"
                        >
                          <span>{{ v.name }}</span>
                          <div
                            class="position-absolute top-0"
                            :style="{ right: '12px' }"
                          >
                            <i
                              class="icon icon-ic_fluent_arrow_circle_right_24_filled"
                              :style="{ color: 'var(--color-cheng)' }"
                            ></i>
                          </div>
                        </div>
                      </router-link>
                    </div>
                  </div>
                </el-col>
                <!-- 右侧-AC题目排行榜 -->
                <el-col :md="11" :xs="24" class="" :style="{}">
                  <div class="my-home-div">
                    <div class="my-home-div-line my-home-AC-list-header">
                      <div class="">
                        <i
                          class="icon icon-ic_fluent_people_team_28_filled"
                        ></i>
                        AC排行
                      </div>
                      <div>
                        <el-date-picker
                          class="my-home-AC-form-date-picker"
                          v-model="formdate"
                          @change="acDateChange"
                          type="daterange"
                          range-separator="至"
                          start-placeholder="开始时间"
                          end-placeholder="结束时间"
                          :shortcuts="shortcuts"
                          unlink-panels
                          size="default"
                        />
                      </div>
                    </div>
                    <div class="my-home-AC-list">
                      <el-scrollbar>
                        <el-table
                          :data="acRank"
                          width="100%"
                          height="550"
                          size="default"
                          table-layout="auto"
                        >
                          <el-table-column
                            type="index"
                            label="排名"
                            min-width="80"
                            width="100"
                          >
                            <template #default="{ $index }">
                              <div class="icon-text">
                                <span
                                  :style="{
                                    width: '30px',
                                    textAlign: 'center',
                                    display: 'inline-block',
                                  }"
                                >
                                  <svg
                                    :style="{ fontSize: '28px' }"
                                    class="icon"
                                    aria-hidden="true"
                                    v-if="$index < 3"
                                  >
                                    <use :xlink:href="svg[$index]" />
                                  </svg>
                                  <span v-else>{{ $index + 1 }}</span>
                                </span>
                              </div>
                            </template>
                          </el-table-column>
                          <el-table-column prop="name" label="昵称" width="">
                            <template #default="{ row }">
                              <router-link
                                v-slot="{ href }"
                                custom
                                :to="{
                                  name: '用户',
                                  query: { userid: row.ID },
                                }"
                              >
                                <el-link :href="href">
                                  {{ row.name }}
                                </el-link>
                              </router-link>
                            </template>
                          </el-table-column>
                          <el-table-column
                            prop="ACcount"
                            label="AC数"
                            min-width="100"
                            width="120"
                          >
                            <template #default="{ row }">
                              {{ row.ACcount || 0 }} ({{ row.df || 0 }}%)
                            </template>
                          </el-table-column>
                        </el-table>
                      </el-scrollbar>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </el-col>
            <!-- 右侧 -->
            <el-col :sm="8" :xs="24" class="" style="width: 500px">
              <div class="home-container-aside" width="500px">
                <div class="col">
                  <!-- 团队公告 v-if="teamInfo?.info"-->
                  <div class="my-home-div" v-if="teamInfo?.info">
                    <div class="my-home-div-line row">
                      <div class="col">
                        <svg class="icon" aria-hidden="true">
                          <use xlink:href="#icon-icon_team_Megaphone"></use>
                        </svg>
                        团队公告
                      </div>
                    </div>
                    <div class="text">
                      <pre class="team-announcement">{{
                        teamInfo?.info
                          ? teamInfo?.info
                          : `欢迎来到 ${teamInfo?.name}`
                      }}</pre>
                    </div>
                  </div>
                  <!-- 学校banner位 el-carousel height="auto" -->
                  <div class="my-home-div">
                    <el-carousel class="home-banner" autoplay height="auto">
                      <el-carousel-item
                        class="home-banner-item"
                        v-for="(item, k) in teamInfo?.other?.banner"
                        :key="k"
                      >
                        <el-image
                          class="home-banner-img"
                          fit="contain"
                          :src="item.url"
                        >
                          <template #error>
                            <div class="image-slot">
                              <el-icon><icon-picture /></el-icon>
                            </div>
                          </template>
                        </el-image>
                      </el-carousel-item>
                      <el-image
                        class="home-banner-img"
                        fit="contain"
                        src="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/saas-banner.png"
                        style="opacity: 0"
                      >
                      </el-image>
                    </el-carousel>
                  </div>
                  <!-- 我的数据 -->
                  <questionnumVue
                    :teamid="teamid"
                    :teamdata="myInfo"
                    :isshow="true"
                    :getuser="user"
                  >
                  </questionnumVue>

                  <!-- 我的积分 -->
                  <!-- <integralnumVue :getuser="user"></integralnumVue> -->

                  <!-- 相关链接 -->
                  <div
                    class="my-home-div"
                    v-for="vo in data.banner.option"
                    :style="{
                      marginTop: '24px',
                      paddingBottom: '12px',
                      minHeight: '380px',
                    }"
                  >
                    <div class="my-home-div-line row">
                      <div class="col">
                        <i
                          class="icon icon-ic_fluent_notebook_question_mark_24_filled"
                        ></i>
                        {{ vo.name }}
                      </div>
                    </div>
                    <div
                      class="jhfontweight cu home-item-list position-relative"
                      v-for="(v, i) in vo.list"
                      :key="'a__a' + i"
                    >
                      <el-link
                        target="_bank"
                        :style="{
                          '--el-link-default-text-color': 'var(--color-22)',
                        }"
                        :underline="false"
                        :href="toLink(v.url!)"
                      >
                        {{ v.name }}
                      </el-link>
                      <div
                        class="position-absolute top-0"
                        :style="{ right: '12px' }"
                      >
                        <i
                          class="icon icon-ic_fluent_arrow_circle_right_24_filled"
                          :style="{ color: 'var(--color-cheng)' }"
                        >
                        </i>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
          <HomeFooter></HomeFooter>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Picture as IconPicture } from "@element-plus/icons-vue";
import { dayjs } from "element-plus";
import { computed, inject, onMounted, reactive, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import HomeFooter from "../../acCoderSaas/views/HomeFooter.vue";
import {
  asyncgetsetup,
  asyncgetteam,
  asyncranking,
  asyncselectdistinctuserquestion,
  asyncselectquestion,
  asyncselectquestionbank,
} from "../../api";
import { Storekey } from "../../interface";
import Study from "../../mysql_interface/studycodemodel";
import ActivityList from "../../ojSass/components/activity/listmenu2.vue";
import questionnumVue from "../../ojSass/views/User/questionnum.vue";
const svg = ["#icon-rank_1", "#icon-rank_2", "#icon-rank_3"];
const dayMs = 3600 * 1000 * 24;
const shortcuts = [
  {
    text: "近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - dayMs * 7);
      return [start, end];
    },
  },
  {
    text: "近一个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - dayMs * 30);
      return [start, end];
    },
  },
  {
    text: "近三个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - dayMs * 90);
      return [start, end];
    },
  },
];

const tenant_id = inject<string | undefined>('tenant_id', undefined)
const router = useRouter();
const data = reactive<Study.Isetup>({ banner: {} });

const store = useStore(Storekey);
const user = computed(() => {
  return store.state.user || {};
});
const teamid = computed(() => {
  return user.value?.teamid;
});
// 默认
const defaultTeamInfo = {
  other: {
    banner: [
      {
        name: "banner01.png",
        url: "https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/saas-banner.png",
      },
    ],
  },
};
const teamInfo = ref<Study.Iteam>(defaultTeamInfo);
// 监听团队切换
watch(
  () => teamid.value,
  (o, n) => {
    if (o !== n) start();
  }
);

// 最近练习
const question = ref("");
const myFinishQ = ref<
  { questionid: number; userid: number; question: Study.Iquestion }[]
>([]);
async function getMyFinishQuestion() {
  const { rows } = await asyncselectdistinctuserquestion({
    _order: "questionid",
    _sortable: "DESC",
    userid: user.value?.ID,
    _limit: 6,
    _offset: 0,
  });
  myFinishQ.value = rows;
}
function goToQuestion(row: {
  questionid: number;
  userid: number;
  question: Study.Iquestion;
}) {
  router.push({
    name: "题目",
    params: { ID: row.question.ID },
    query: { userId: user.value.ID },
  });
}

const options = ref<Study.Iquestion[]>([]);
const loading = ref(false);
const remoteSelectQuestion = async (value: string) => {
  if (value) {
    loading.value = true;
    const { rows } = await asyncselectquestion({
      _offset: 0,
      _limit: 20,
      _order: "ID",
      _sortable: "ASC",
      _like: [
        ["ID", value],
        ["name", value],
      ],
      range: "public",
    });
    loading.value = false;
    options.value = rows;
  } else {
    options.value = [];
  }
};
// 仅当 modelValue 改变时，当输入框失去焦点或用户按Enter时触发
async function qChange(value: string) {
  if (!value) {
    return;
  }
  // 跳转到题目
  router.push({
    name: "题目",
    params: { ID: value },
    query: {},
  });
}

// AC排行
const formdate = ref<[Date, Date]>([
  new Date(Date.now() - dayMs * 30),
  new Date(),
]);
const times = computed<[string, string]>(() => {
  if (!formdate.value) {
    // 不能设为空值 默认最近30天的数据
    formdate.value = [new Date(Date.now() - dayMs * 30), new Date()];
  }
  return [
    dayjs(formdate.value[0]).format("YYYY-MM-DD 00:00:00"),
    dayjs(formdate.value[1]).format("YYYY-MM-DD 23:59:59"),
  ];
});
function acDateChange() {
  getTeamAcRank();
}

const acRank = ref<
  {
    ID?: number;
    name?: string;
    ACcount?: number;
    df?: number;
    headportrait?: string;
  }[]
>([]);
const myInfo = ref<{
  ID?: number;
  name?: string;
  ACcount?: number;
  df?: number;
  headportrait?: string;
}>({});
async function getMyInfo() {
  if (teamid.value && user.value?.ID) {
    try {
      const t = await asyncranking({
        teamid: teamid.value,
        userid: user.value?.ID,
        formdate: Date.now() - 1000 * 60 * 60 * 24 * 365,
        todate: new Date(),
      });
      const [data] = t.ACrank.map((e) => {
        const user = t.user.find((z) => z.ID === e.userid);
        return {
          ...e,
          ...user,
          // count 题目AC数（测试点全AC）
          ACcount: e.count,
          // resultdataarrlength-测试点总数 resultdataarraclength-测试点AC总数
          df: Math.floor(
            (Number(e.resultdataarrlength) / Number(e.resultdataarraclength)) *
              100
          ),
        };
      });
      myInfo.value = data;
    } catch (e) {}
  }
}
async function getTeamAcRank() {
  if (teamid.value) {
    try {
      const t = await asyncranking({
        teamid: teamid.value,
        formdate: times.value[0],
        todate: times.value[1],
      });
      acRank.value = t.user
        .map((e) => {
          const userRankInfo = t.ACrank.find((z) => z.userid === e.ID);
          return {
            ...e,
            ...userRankInfo,
            ACcount: userRankInfo?.count || 0,
            df: Math.floor(
              (Number(userRankInfo?.resultdataarrlength) /
                Number(userRankInfo?.resultdataarraclength)) *
                100
            ),
          };
        })
        .sort((a, b) => {
          return b.df - a.df;
        })
        .sort((a, b) => {
          return b.ACcount - a.ACcount;
        })
        .slice(0, 20);
    } catch (e) {
      // ElMessage.error('没有查询')
    }
  }
}

// 比赛
const getactivity = computed(() => {
  return store.state.activity?.rows || [];
});

const 赛前集训 = ref<Study.Iquestionbank[]>([]);
const 能力测评 = ref<Study.Iquestionbank[]>([]);

onMounted(async () => {
  start();
});

// // 题目
// const myquestion = ref<Studycodemodel.Iquestion[]>([])
// // 提单
// const myquestionbank = ref<Studycodemodel.Iquestionbank[]>([])
async function start() {
  console.log("home.vue start");
  
  if (teamid.value) {
    // 获取团队数据
    const teamData = await asyncgetteam({ ID: teamid.value as number });
    // delete teamData.other
    // 合并other
    teamInfo.value = {
      ...teamData,
      other: Object.assign({}, defaultTeamInfo.other, teamData.other),
    };
    store.dispatch("actionactivity", {
      teamid: teamid.value,
      tenant_id,
      _limit: 5,
    });
  }

  const { banner = {} } = await asyncgetsetup();
  data.banner = banner;
  store.dispatch("actionquestion", {
    _limit: 5,
    _order: "ID",
    _sortable: "DESC",
  });
  getMyFinishQuestion();
  getTeamAcRank();
  getMyInfo();

  const questionbank_1 = await asyncselectquestionbank({
    _limit: 11,
    _offset: 0,
    _order: "top",
    purpose: "能力测评",
    _sortable: "ASC",
  });
  const questionbank_2 = await asyncselectquestionbank({
    _limit: 5,
    _offset: 0,
    _order: "top",
    purpose: "赛前集训",
    _sortable: "ASC",
    teamid: {
      or: {
        is: null,
        in: [teamid.value],
      },
    },
    usertype: ["public", "team"],
  });
  赛前集训.value = questionbank_2.rows;
  能力测评.value = questionbank_1.rows;
}

// 相关链接的跳转 数据库返回的是 https://oj.hterobot.com/#/article/100024  自己拼接
function toLink(url: string) {
  if (!url.includes("oj.hterobot.com")) {
    return url;
  }
  const { origin, pathname } = window.location;
  let path = url.split("#")[1];
  // console.log(origin, pathname, path)
  return `${origin}${pathname}#${path}`;
}
</script>

<style scoped>
#home {
  padding: var(--container-margin) 5% 0;
  margin: var(--container-margin) 0rem 0 0rem;
  /* 外边距 */
  --container-margin: 20px;
  --container-header-height: 10vh;
  --container-bg-color: #fff;
}

.home-container-content {
  padding: 0;
}

.flex-jc-space-between {
  display: flex;
  justify-content: space-between;
}

.home-item-list {
  background: rgba(255, 255, 255, 0.5);
  font-size: 14px;
  border: 1px solid rgba(0, 0, 0, 0.06);
  border-radius: 2px;
}

.home-item-list a {
  display: block;
}

.home-item-list:hover {
  background-color: var(--color-f5);
  color: var(--color-cheng);
}

.my-home-div-line i {
  font-size: 16px;
}

.my-home-div .text {
  padding: 12px 14px;

  pre {
    background: none;
    border: none;
    margin: 0;
    padding: 0;
    font-size: 14px;
    font-family: Microsoft YaHei, Arial;
  }
}

/* 我的题目 */
.my-home-question-input-box {
  height: 80px;
  padding: 14px;
  max-width: 270px;

  input {
    height: 40px;
  }
}

.my-home-question-box {
  height: 80px;
  padding: 4px 14px;
}

.my-home-question {
  display: flex;
  justify-content: space-between;
  padding: 4px 4px 0;
  margin: 2px 4px;
  background: rgba(255, 255, 255, 0.5);
  /* border: 1px solid rgba(0, 0, 0, 0.06);
  border-radius: 2px; */
}

.my-home-question:hover {
  background-color: var(--color-f5);
  color: var(--color-cheng);
}

/* 查看更多 */
.href {
  text-decoration: none;
  color: var(--color-cheng);
  font-size: 14px;
  font-weight: 400;
}

.jhfontweight {
  height: 44px;
  margin: 12px;
  line-height: 44px;
  margin-bottom: 0px;
  padding-left: 12px;
  padding-right: 12px;
  font-size: 14px;
  overflow: hidden;
}

.jhfontweight span {
  overflow: hidden;
  display: inline-block;
}

/* ojSass home banner*/
.home-banner {
  height: auto !important;
}

.home-banner-item {
  width: 100%;
  height: 100%;
  height: auto !important;
  background: white;
}

.home-banner-img {
  height: auto !important;
  object-fit: contain;
}

.my-home-AC-list-header {
  display: flex;
  justify-content: space-between;
  /* align-items: center;
  flex-wrap: wrap;
  height:auto !important; */
}

.my-home-AC-list {
  padding: 0 14px 14px;
}
</style>

<style>
.my-home-AC-list-header .my-home-AC-form-date-picker {
  max-width: 270px !important;
}

/* 轮播图底部有一部分留白需要处理 */
.home-banner-item .el-image {
  overflow: visible;
  height: auto !important;
}

.home-banner .el-carousel__container {
  min-height: auto;
  height: auto !important;
}
</style>
